<!--
 * @Author: ChaiHongJun
 * @Date: 2021-07-24 11:41:46
 * @LastEditors: ChaiHongJun
 * @LastEditTime: 2021-07-24 14:58:35
 * @version: 
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3.axios实例对象</title>
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2 class="page-header">axios实例对象</h2>
      <button class="btn btn-primary" type="button">GET(段子)</button>
      <button class="btn btn-warning" type="button">POST(美图)</button>

      <div class="card">
        <div class="card-body">
          <p>axios 响应的返回对象包含如下几个对象</p>
          <ul class="list-group list-group-flush">
            <li class="list-group-item">config (请求配置)</li>
            <li class="list-group-item">headers (响应头)</li>
            <li class="list-group-item">data (响应的数据，也就是body)</li>
            <li class="list-group-item">request (XMLHttpRequest 原生对象)</li>
            <li class="list-group-item">status (响应状态码)</li>
            <li class="list-group-item">statusText (响应状态字符串)</li>
          </ul>
        </div>
      </div>
    </div>
  </body>
</html>

<script>
  window.addEventListener("load", () => {
    const buttons = document.querySelectorAll("button");

    const instance = axios.create({
      baseURL: "https://api.apiopen.top",
      timeout: 3000,
    });

    let methods = ["GET", "POST"];
    let url = ["/getJoke", "/getImages"];
    let data = {
      page: 1,
      count: 10,
    };

    for (let i = 0; i < buttons.length; i++) {
      buttons[i].addEventListener("click", () => {
        instance({
          method: methods[i],
          url: url[i],
          data: i ? data : null,
        }).then((response) => {
          console.log(response);
        });
      });
    }
  });
</script>
